/**
 * 拆书分析服务
 * 提供拆书记录相关的API调用
 */
import { BaseService } from '../../shared/services/base-service'
import type { ApiResponse } from '../../../types/api' 
import SockJS from 'sockjs-client'
import { Client as Stomp } from '@stomp/stompjs'

// 拆书记录类型定义
export interface BookAnalysisRecord {
  id?: number
  userId?: number
  name: string
  description?: string
  author?: string
  status?: 'pending' | 'processing' | 'completed' | 'failed'
  sourceType: 'URL' | 'FILE'
  sourcePath?: string
  sourceUrl?: string
  systemPromptId?: number
  modelId?: number
  progress?: number
  startTime?: Date
  endTime?: Date
  errorMessage?: string
  createTime?: Date
  updateTime?: Date
}

// 拆书结果类型定义
export interface BookAnalysisResult {
  id?: number
  recordId: number
  resultType: 'OVERVIEW' | 'SUMMARY' | 'STRUCTURE' | 'CHARACTERS' | 'THEMES'
  title?: string
  content: string
  chapterIndex?: number
  createTime?: Date
}

// 创建记录请求
export interface CreateRecordRequest {
  name: string
  userPrompt?: string
  sourceType: 'URL' | 'FILE'
  sourceUrl?: string
  sourcePath?: string
  systemPromptId?: number
  modelId?: number
  file?: File
}

// 更新记录请求
export interface UpdateRecordRequest {
  id: number
  name?: string
  sourceType?: 'URL' | 'FILE'
  sourceUrl?: string
  sourcePath?: string
  systemPromptId?: number
  modelId?: number
}

// 记录状态响应
export interface RecordStatusResponse {
  recordId: number
  status: string
  progress: number
  startTime?: Date
  endTime?: Date
  errorMessage?: string
  timestamp: number
}

// WebSocket消息类型
export interface WebSocketMessage {
  type: 'status' | 'progress' | 'completion' | 'error'
  recordId: number
  status?: string
  progress?: number
  message?: string
  error?: string
  errorMessage?: string
  timestamp: number
}

export class BookAnalysisService extends BaseService {
  private static instance: BookAnalysisService

  private constructor() {
    super()
  }

  public static getInstance(): BookAnalysisService {
    if (!BookAnalysisService.instance) {
      BookAnalysisService.instance = new BookAnalysisService()
    }
    return BookAnalysisService.instance
  }

  /**
   * 获取用户的拆书记录列表
   */
  async getUserRecords(): Promise<ApiResponse<BookAnalysisRecord[]>> {
    return this.get<BookAnalysisRecord[]>('/book-analysis/records')
  }

  /**
   * 根据ID获取拆书记录
   */
  async getRecordById(id: number): Promise<ApiResponse<BookAnalysisRecord>> {
    return this.get<BookAnalysisRecord>(`/book-analysis/records/${id}`)
  }

  /**
   * 创建拆书记录并开始分析
   */
  async createRecordAndStartAnalysis(recordData: CreateRecordRequest): Promise<ApiResponse<BookAnalysisRecord>> {
    // 统一使用FormData方式发送请求
    const formData = new FormData()
    formData.append('name', recordData.name)
    if (recordData.userPrompt) {
      formData.append('userPrompt', recordData.userPrompt)
    }
    formData.append('sourceType', recordData.sourceType)
    if (recordData.sourceUrl) {
      formData.append('sourceUrl', recordData.sourceUrl)
    }
    if (recordData.sourcePath) {
      formData.append('sourcePath', recordData.sourcePath)
    }
    if (recordData.systemPromptId) {
      formData.append('systemPromptId', recordData.systemPromptId.toString())
    }
    if (recordData.modelId) {
      formData.append('modelId', recordData.modelId.toString())
    }
    if (recordData.file) {
      formData.append('file', recordData.file)
    }

    return this.post<BookAnalysisRecord>('/book-analysis/records', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  /**
   * 更新拆书记录
   */
  async updateRecord(recordData: UpdateRecordRequest): Promise<ApiResponse<BookAnalysisRecord>> {
    return this.put<BookAnalysisRecord>(`/book-analysis/records/${recordData.id}`, recordData)
  }

  /**
   * 删除拆书记录
   */
  async deleteRecord(id: number): Promise<ApiResponse<string>> {
    return this.delete<string>(`/book-analysis/records/${id}`)
  }

  /**
   * 重新开始分析
   */
  async restartAnalysis(recordId: number): Promise<ApiResponse<BookAnalysisRecord>> {
    return this.post<BookAnalysisRecord>(`/book-analysis/records/${recordId}/restart`)
  }

  /**
   * 获取记录状态
   */
  async getRecordStatus(recordId: number): Promise<ApiResponse<RecordStatusResponse>> {
    return this.get<RecordStatusResponse>(`/book-analysis/records/${recordId}/status`)
  }

  /**
   * 获取记录结果
   */
  async getRecordResults(recordId: number): Promise<ApiResponse<BookAnalysisResult[]>> {
    return this.get<BookAnalysisResult[]>(`/book-analysis/records/${recordId}/results`)
  }

  /**
   * 导出记录结果
   */
  async exportRecordResults(recordId: number): Promise<ApiResponse<{ downloadUrl: string, fileName: string }>> {
    return this.get<{ downloadUrl: string, fileName: string }>(`/book-analysis/records/${recordId}/export`)
  }

  /**
   * 创建WebSocket连接以接收记录进度更新
   */
  createRecordProgressConnection(recordId: number, callbacks: {
    onStatus?: (message: WebSocketMessage) => void
    onProgress?: (message: WebSocketMessage) => void
    onCompletion?: (message: WebSocketMessage) => void
    onError?: (message: WebSocketMessage) => void
  }): any {
    // 获取WebSocket基础URL
    const wsBaseUrl = import.meta.env.VITE_WS_BASE_URL || 'http://127.0.0.1:8080'
    const wsUrl = `${wsBaseUrl}/ws-book-analysis`
    
    console.log('尝试连接书籍分析WebSocket:', wsUrl)
    
    // 创建SockJS连接
    const socket = new SockJS(wsUrl)
    
    // 创建STOMP客户端 - 使用新版本API
    const stompClient = new Stomp({
      webSocketFactory: () => socket,
      debug: (str) => {
        console.log(str);
      },
      reconnectDelay: 5000,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000,
    })
    
    // 连接成功回调
    stompClient.onConnect = (frame) => {
      console.log('STOMP连接已建立', frame);
      
      // 订阅记录进度更新
      stompClient.subscribe(`/topic/book-analysis/progress/${recordId}`, (message) => {
        try {
          const rawMessage = JSON.parse(message.body)
          const wsMessage: WebSocketMessage = {
            type: 'progress',
            recordId: rawMessage.recordId || recordId,
            progress: rawMessage.progress,
            message: rawMessage.message,
            timestamp: rawMessage.timestamp || Date.now()
          }
          callbacks.onProgress?.(wsMessage)
        } catch (error) {
          console.error('解析进度消息失败:', error);
        }
      })
      
      // 订阅记录状态更新
      stompClient.subscribe(`/topic/book-analysis/status/${recordId}`, (message) => {
        try {
          const rawMessage = JSON.parse(message.body)
          const wsMessage: WebSocketMessage = {
            type: 'status',
            recordId: rawMessage.recordId || recordId,
            status: rawMessage.status.toLowerCase(), // 确保状态为小写
            progress: rawMessage.progress,
            errorMessage: rawMessage.errorMessage,
            timestamp: rawMessage.timestamp || Date.now()
          }
          callbacks.onStatus?.(wsMessage)
        } catch (error) {
          console.error('解析状态消息失败:', error);
        }
      })
      
      // 订阅记录完成通知
      stompClient.subscribe(`/topic/book-analysis/completion/${recordId}`, (message) => {
        try {
          const rawMessage = JSON.parse(message.body)
          const wsMessage: WebSocketMessage = {
            type: 'completion',
            recordId: rawMessage.recordId || recordId,
            status: rawMessage.status.toLowerCase(), // 确保状态为小写
            message: rawMessage.message,
            timestamp: rawMessage.timestamp || Date.now()
          }
          callbacks.onCompletion?.(wsMessage)
        } catch (error) {
          console.error('解析完成消息失败:', error);
        }
      })
    }
    
    // 连接错误回调
    stompClient.onStompError = (frame) => {
      console.error('书籍分析STOMP连接错误:', frame);
      const wsMessage: WebSocketMessage = {
        type: 'error',
        recordId: recordId,
        status: 'failed',
        errorMessage: 'WebSocket连接失败，书籍分析进度更新将不可用',
        timestamp: Date.now()
      }
      callbacks.onError?.(wsMessage)
      // WebSocket连接失败不影响书籍分析功能，只是无法实时更新进度
    }
    
    // 激活连接
    stompClient.activate()
    
    return stompClient
  }
}

// 导出单例实例
export const bookAnalysisService = BookAnalysisService.getInstance()